<template>
  <div class="searchContainer">
    <!-- 关键字搜索 -->
    <div class="search">
      <div class="keyWords">
        <van-search
          v-model="keyword"
          autocomplete="off"
          clearable
          clear-icon="clear"
          clear-trigger="focus"
          class="vanSearch"
          show-action
          placeholder="请输入搜索关键词"
          shape="round"
          @cancel="
            () => {
              router.go(-1)
            }
          "
          @search="handleSearch"
          @update:model-value="debounceInput"
        />
      </div>
    </div>

    <div v-show="!keyword">
      <!-- 历史记录 -->
      <div class="historyRecords" v-if="historySearchList.length > 0">
        <div class="historyTop">
          <span class="left">历史记录</span>
          <van-icon class="right" name="delete-o" size="18" @click="resetHistoryList" />
        </div>
        <div class="historyBottom" @click="handleTouchHistoryTag">
          <span class="historyTag" v-for="(item, index) in historySearchList" :key="index">{{ item }}</span>
        </div>
      </div>

      <!-- 热门搜索 -->
      <div class="hot">
        <div class="hotSearch">热门搜索</div>
        <div class="historyBottom hotBottom" @click="handleTouchHistoryTag">
          <span class="historyTag" :class="{ active: hot.highlight === 1 }" v-for="(hot, index) in hotKeywordList" :key="index">{{
            hot.keyword
          }}</span>
        </div>
      </div>
    </div>

    <!-- 搜索联系下拉框 -->
    <div v-show="keyword" class="dropdown">
      <ul class="itemList">
        <li class="item" v-for="(item, index) in lenovoData" :key="index" @click="handleTimeTag(item)">
          <van-nav-bar class="navBar">
            <template #left>
              <span class="navText">{{ item }}</span>
            </template>
            <template #right>
              <van-icon class="navIcon" name="arrow" size="16" color="gray" />
            </template>
          </van-nav-bar>
        </li>
      </ul>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
  name: 'SearchPage'
})
</script>
<script lang="ts" setup>
import { onMounted, ref, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import useSearchStore from '@/stores/search'
import _ from 'lodash'
// 创建路由实例
const router = useRouter()
// 创建仓库实例
const searchStore = useSearchStore()
// 从仓库中取出 数据
const { lenovoData, hotKeywordList } = storeToRefs(searchStore)
// 定义变量
const keyword = ref('') // 搜索关键字
const historySearchList = ref<string[]>([]) // 搜索历史记录数组

// 获取热门搜索数据
const getHotKeywordList = () => {
  searchStore.getHotData()
}

/* 历史记录相关 */
// 从本地localStorage中获取历史记录
const getHistoryList = () => {
  if (JSON.parse(localStorage.getItem('historySearch') as string)) {
    historySearchList.value = JSON.parse(localStorage.getItem('historySearch') as string)
  } else {
    historySearchList.value = []
  }
}
// 在本地存储搜索记录
const setHistoryList = (item = '') => {
  if (item === '') {
    item = keyword.value
  }
  getHistoryList()
  // 判断要存储的值是否存在
  if (!historySearchList.value.includes(item)) {
    // 如果不存在，就添加
    historySearchList.value.unshift(item)
    localStorage.setItem('historySearch', JSON.stringify(historySearchList.value))
  }
}
// 清空本地搜索记录
const resetHistoryList = () => {
  localStorage.removeItem('historySearch')
  historySearchList.value = []
}

// 点击历史记录或热门搜索tag去搜索
const handleTouchHistoryTag = (e: any) => {
  setHistoryList(e.target.innerText) // 添加本地记录
  router.push({
    path: '/search/goods',
    query: {
      keyword: e.target.innerText
    }
  })
}
// 点击实时联想去搜索对应内容
const handleTimeTag = (item: string) => {
  setHistoryList(item) // 添加本地记录
  router.push({
    path: '/search/goods',
    query: {
      keyword: item
    }
  })
}

/** 用户输入 */
const handleInput = (value: string) => {
  if (value) {
    // 请求实时联想数据
    searchStore.getTimeLenovoData(keyword.value)
  } else {
    // 用户清空时，重置实时联想数据
    searchStore.resetTimeData()
  }
}
// 对用户输入行为进行节流处理
const debounceInput = _.debounce(handleInput, 500)

/** 用户搜索行为 */
const handleSearch = (value: string) => {
  // 保存搜索关键字到localStorage中
  setHistoryList()
  // 携带搜索关键字跳转到商品列表
  router.push({
    path: '/search/goods',
    query: {
      keyword: keyword.value
    }
  })
  keyword.value = '' // 重置关键字
}

onMounted(() => {
  getHistoryList() // 获取历史记录
  getHotKeywordList() // 组件挂载完成时获取热门搜索数据
})
// 组件卸载前，做清除工作
onBeforeUnmount(() => {
  searchStore.resetTimeData() // 清空实时联想数据
  searchStore.resetHotData() // 清空热门搜索数据
})
</script>

<style lang="less" scoped>
.searchContainer {
  height: 100%;
  background-color: #eee;
  // 关键字搜索
  .search {
    box-sizing: border-box;
    padding: 10px 15px;
    width: 100%;
    background-color: #fff;
    .keyWords {
      width: 100%;
      height: 44px;
      position: relative;
      .vanSearch {
        :deep(.van-search__action) {
          transform: translateX(6px);
        }
        :deep(.van-field__control::placeholder) {
          color: rgba(0, 0, 0, 0.8);
        }
      }
    }
  }
  // 历史记录
  .historyRecords {
    box-sizing: border-box;
    width: 100%;
    background-color: #fff;
    padding: 0 15px;
    margin-bottom: 10px;
    .historyTop {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .left {
        color: #999;
        font-size: 14px;
        font-weight: 400;
        margin-left: 6px;
      }
    }
  }

  // tag
  .historyBottom {
    margin-top: 16px;
    padding-left: 6px;
    box-sizing: border-box;
    display: flex;
    flex-wrap: wrap;
    .historyTag {
      height: 22px;
      text-align: center;
      line-height: 22px;
      border: 1px solid #999;
      border-radius: 4px;
      font-size: 12px;
      color: #333;
      padding: 0 10px;
      margin: 0 16px 16px 0;
      &.active {
        border-color: red;
        color: red;
      }
    }
  }

  // 热门搜索
  .hot {
    box-sizing: border-box;
    width: 100%;
    background-color: #fff;
    padding: 0 15px;
    .hotSearch {
      height: 40px;
      color: #999;
      font-size: 14px;
      font-weight: 400;
      margin-left: 6px;
      line-height: 40px;
    }
    .hotBottom {
      margin-top: 6px;
    }
  }

  // 实时搜索
  .dropdown {
    position: absolute;
    width: 100%;
    padding: 0 15px;
    box-sizing: border-box;
    left: 0;
    top: 50px;
    background-color: #fff;
    .item:last-child {
      border-bottom: none;
    }
    .item {
      border-bottom: 2px solid #ccc;
      height: 46px;
      .navBar {
        .navText {
          transform: translate(-10px, 2px);
        }
        .navIcon {
          transform: translate(14px, 4px);
        }
      }
    }
  }
}
</style>
